<template>
	<view class="bgf pd20 box-b" style="padding-bottom: 180rpx">
		<view class="f34 ac jsa fw600 lh80 text-center">{{ currentDate }}</view>
		<view class="text-box">
			<view class="tab df lh80">
				<view
					class="flex-1 f32 g3"
					@tap="setCurrent(item.type)"
					:class="current === item.type ? 'active' : ''"
					v-for="(item, index) in textArr"
					:key="index"
					>{{ item.name }}</view
				>
			</view>
			<view class="input-h" v-if="current === 'text'">
				<textarea
					v-model="paramsData.scheduleContent"
					placeholder="日程内容、描述"
					class="pd20"
				></textarea>
			</view>
			<!-- <view class="" v-if="current === 'voice'"> -->
			<diy-record
				v-if="current === 'voice'"
				:context="voiceDTOS.voiceText"
				:audioUrl="voiceDTOS.voiceUrl"
				:voliceTime="voiceDTOS.voiceDuration"
				@input="textinput($event, tempIndex)"
				@upload="getRecordFile($event, tempIndex)"
			></diy-record>
			<!-- </view> -->
		</view>
		<view class="content mt20">
			<view class="form-item df df-warp">
				<label for="">日期</label>
				<view class="right-content flex-1 df df-warp ac">
					<text class="label" :class="{ active: !entryTime }"
						>今天</text
					>
					<uni-datetime-picker type="date" v-model="entryTime">
						<text class="label" :class="{ active: entryTime }">{{
							entryTime
								? dayjs(entryTime).format('MM-DD')
								: '选择日期'
						}}</text>
					</uni-datetime-picker>
				</view>
			</view>
			<view class="form-item df df-warp">
				<label for="">时间</label>
				<view class="right-content flex-1">
					<text
						class="label"
						@tap="chooseTime(2, 'start')"
						:class="{ active: paramsData.dateType == 2 }"
						>{{ paramsData.scheduleStartTime }}</text
					>
					~
					<text
						class="label"
						@tap="chooseTime(2, 'end')"
						:class="{ active: paramsData.dateType == 2 }"
						>{{ paramsData.scheduleEndTime }}</text
					>
					<text
						class="label"
						@tap="chooseTime(1)"
						:class="{ active: paramsData.dateType == 1 }"
						>全天</text
					>
				</view>
			</view>
			<view class="form-item df df-warp">
				<label for="">优先级</label>
				<view class="right-content flex-1">
					<view
						class="label level"
						@tap="selectLevel(item)"
						:class="
							paramsData.schedulePriority == item.key
								? 'active'
								: ''
						"
						v-for="(item, index) in levelList"
						:key="index"
					>
						{{ item.value }}
					</view>
				</view>
			</view>
			<view class="form-item df df-warp">
				<label for="">类型</label>
				<view class="right-content flex-1 type">
					<view
						class="label typeLabel"
						@tap="selectType(item)"
						:class="
							paramsData.scheduleType === item.key ? 'active' : ''
						"
						v-for="(item, index) in typeList"
						:key="index"
					>
						{{ item.value }}
					</view>
				</view>
			</view>
			<view class="form-item df df-warp">
				<label for="">成员</label>
				<view class="right-content flex-1">
					<view
						class="label"
						@tap="chooseUserItem(item)"
						:class="userType === item.value ? 'active' : ''"
						v-for="(item, index) in userList"
						:key="index"
						>{{ item.text }}</view
					>
					<view class="">
						<text
							class="mb20 ml20"
							v-for="item in userData.filter((u) => u.showFlag)"
							:key="item.id"
							>{{ item.name }}</text
						>
					</view>
				</view>
			</view>
			<view class="form-item df df-warp">
				<label for="">标签</label>
				<view class="right-content flex-1">
					<view
						class="label"
						@tap="selectLabel(item)"
						:class="
							paramsData.scheduleLabelId === item.key
								? 'active'
								: ''
						"
						v-for="(item, index) in labelList"
						:key="index"
					>
						{{ item.value }}
					</view>
				</view>
			</view>
			<view class="form-item df df-warp">
				<label for="">通知</label>
				<view class="right-content flex-1">
					<view
						class="label"
						@tap="selectNotice(item)"
						:class="
							paramsData.noticeType === item.key ? 'active' : ''
						"
						v-for="(item, index) in noticeList"
						:key="index"
					>
						{{ item.value }}
					</view>
				</view>
			</view>
		</view>
		<view class="bottom-button-bd df jsc" v-if="paramsData.id">
			<button
				class="primary-button w40"
				@tap.stop="$noMultipleClicks(onSubmit, {})"
			>
				保存修改
			</button>
			<button
				class="primary-button w40"
				@tap.stop="$noMultipleClicks(finish, {})"
			>
				完成
			</button>
		</view>
		<view class="bottom-button-bd df jsc" v-else
			><button
				class="primary-button w90"
				@tap.stop="$noMultipleClicks(onSubmit, {})"
			>
				确定
			</button></view
		>

		<!-- <view class="add" @tap="add"><button class="primary-button">确定</button></view> -->
		<!-- 选择成员 -->
		<user-list
			ref="userRefs"
			:userList="userData"
			@complete="updateUserList"
		></user-list>
		<!--时间选择-->
		<diy-dateselect
			:show="dateSelectShow"
			@close="closeChooseDate"
			@submit="submitChooseDate"
		></diy-dateselect>
		<!-- 完成操作 -->
		<operateComplete ref="operateCompleteRef" @complete="getList" />
	</view>
</template>

<script>
import userList from './compoents/userList/userList.vue'
import operateComplete from './components/operateCompletion/operateCompletion.vue'
const dayjs = require('@/common/dayjs.min.js')
export default {
	components: {
		userList,
		operateComplete,
		// remarkAndRecord
	},
	data() {
		return {
			dayjs,
			current: 'voice',
			value: '',
			entryTime: '',
			currentDate: '',
			textArr: [
				{ name: '文字输入', type: 'text' },
				{ name: '语音输入', type: 'voice' },
			],
			userList: [
				{ text: '无', value: 1 },
				{ text: '选择成员', value: 2 },
			],
			levelList: [],
			typeList: [],
			labelList: [],
			noticeList: [],
			dateSelectShow: false,
			paramsData: {
				dateType: 2,
				scheduleStartTime: '',
				scheduleEndTime: '',
				scheduleStandardDate: '',
				scheduleContent: '',
				schedulePriority: 1,
				scheduleLabelId: 1,
				scheduleType: 1,
				partUserIds: [],
				noticeType: 0,
				voiceDTOS: [],
			},
			noClick: true,
			scheduleId: '',
			voiceDTOS: {
				voiceUrl: '',
				voiceDuration: 0,
				voiceText: '',
			},
			currentDateType: 'startTime',
			userType: 1,
			userData: [],
		}
	},
	methods: {
		// 设置输入方式
		setCurrent(type) {
			this.current = type
		},
		swithTime() {
			this.paramsData.dateType = 2
		},
		finish() {
			this.$refs.operateCompleteRef.init(this.paramsData)
		},
		getList() {
			uni.$emit('refreshData', 1)
			uni.navigateBack({
				delta: 1,
				success() {
					const page = getCurrentPages().pop() //跳转页面成功之后
					if (!page) return
					page.onLoad({ refresh: true }) //如果页面存在，则调用 onLoad 方法
				},
			})
		},
		getUserData() {
			this.$request
				.request('user-web/user/queryPageByDefaultRole', {
					method: 'post',
					data: { roleIds: [-3, -8], pageIndex: 1, pageSize: 500 },
				})
				.then((res) => {
					let data = res.data.data
					if (data) {
						data.map((item) => {
							item.showFlag = false
						})
						data = data.filter(
							(item) => item.id !== uni.getStorageSync('userId')
						)
					}
					this.userData = data || []
				})
		},
		closeChooseDate(val) {
			// this.currentDateType = val
			this.dateSelectShow = false
		},
		submitChooseDate(val) {
			if (this.currentDateType == 'start') {
				this.paramsData.scheduleStartTime = val[1]
			} else {
				this.paramsData.scheduleEndTime = val[1]
			}
		},
		chooseUserItem(data) {
			this.userType = data.value
			if (data.value == 2) {
				this.$refs.userRefs.init()
			}
		},
		updateUserList(index) {
			this.userData[index].showFlag = !this.userData[index].showFlag
			this.$set(this.userData, index, this.userData[index])
		},
		//选择优先级
		selectLevel(data) {
			this.paramsData.schedulePriority = data.key
		},
		//选择日程类型
		selectType(data) {
			this.paramsData.scheduleType = data.key
		},
		//选择标签
		selectLabel(data) {
			this.paramsData.scheduleLabelId = data.key
		},
		// 选择通知
		selectNotice(data) {
			this.paramsData.noticeType = data.key
		},
		chooseTime(type, timeDate) {
			this.paramsData.dateType = type
			if (type == 1) {
				// this.paramsData.scheduleStartTime = ''
				// this.paramsData.scheduleEndTime = ''
			} else {
				this.currentDateType = timeDate
				this.dateSelectShow = true
			}
		},
		textinput(remark, tempIndex) {
			this.voiceDTOS.voiceText = remark
		},
		//整改项音频
		getRecordFile(volice, tempIndex) {
			this.voiceDTOS.voiceUrl = volice.remark
			this.voiceDTOS.voiceDuration = volice.time
			this.voiceDTOS.voiceText = volice.voiceText
		},
		//获取标签
		getLabel(id) {
			this.$request
				.request('carer-platform/work/log/schedule/scheduleEnum', {
					method: 'post',
					data: { type: id },
				})
				.then((res) => {
					let { data } = res
					switch (id) {
						case 1:
							this.levelList = data
							break
						case 2:
							this.typeList = data.filter(
								(item) => item.key !== 3
							)
							break
						case 3:
							this.noticeList = data
							break
						case 9:
							this.labelList = data
							break
						default:
							break
					}
				})
		},
		writeLog(id) {
			console.log(id)
			this.$request
				.request('carer-platform/work/log/schedule/writeToCalendar', {
					method: 'post',
					data: {
						scheduleId: id,
					},
				})
				.then((res) => {
					let { data } = res

					if (res.data) {
						uni.showToast({
							title: '已添加日历,同步数据完成',
							icon: 'none',
						})
						setTimeout(() => {
							uni.$emit('refreshData', 1)
							uni.navigateBack({
								delta: 1,
								success() {
									const page = getCurrentPages().pop() //跳转页面成功之后
									if (!page) return
									page.onLoad({ refresh: true }) //如果页面存在，则调用 onLoad 方法
								},
							})
						}, 1000)
						// this.$refs.popupDialog.close()
						// this.$emit('complete')
					}
				})
		},
		//提交数据
		onSubmit() {
			console.log(1)
			let ids = this.userData.filter((item) => item.showFlag)
			ids = ids.map((item) => {
				return item.id
			})
			let params = {
				...this.paramsData,
				// ...this.voiceDTOS,
				partUserIds: ids,
				voiceDTOS: [],
				scheduleStandardDate: this.entryTime
					? this.entryTime
					: this.currentDate,
				orgId: uni.getStorageSync('orgId'),
			}
			if (this.paramsData.id) {
				params.scheduleId = this.scheduleId
			}
			if (
				this.voiceDTOS.voiceText == '' &&
				this.paramsData.scheduleContent === ''
			) {
				uni.showToast({
					title: '文字输入或者语音输入两者不能为空',
					icon: 'none',
				})
				return
			}
			if (this.voiceDTOS.voiceUrl) {
				params.voiceDTOS.push({
					voiceUrl: this.voiceDTOS.voiceUrl,
					voiceDuration: this.voiceDTOS.voiceDuration,
					voiceText: this.voiceDTOS.voiceText,
				})
			}
			let url = this.paramsData.id
				? 'carer-platform/work/log/schedule/updateSchedule'
				: 'carer-platform/work/log/schedule/addSchedule'
			this.$request
				.request(url, { method: 'post', data: params })
				.then((res) => {
					let { data } = res
					if (data) {
						if (this.paramsData.scheduleType == 2) {
							let that = this
							let startTimeStr = ''
							let endTimeStr = ''
							if (this.paramsData.dateType == 1) {
								startTimeStr =
									params.scheduleStandardDate +
									' ' +
									'00:00:00'
							} else {
								startTimeStr =
									params.scheduleStandardDate +
									' ' +
									params.scheduleStartTime +
									':00'
								endTimeStr =
									params.scheduleStandardDate +
									' ' +
									params.scheduleEndTime +
									':00'
							}

							wx.addPhoneCalendar({
								title: that.paramsData.scheduleContent
									? that.paramsData.scheduleContent
									: that.voiceDTOS.voiceText,
								startTime:
									new Date(
										startTimeStr.replace(/-/g, '/')
									).getTime() / 1000, //unix 时间戳
								endTime:
									new Date(
										endTimeStr.replace(/-/g, '/')
									).getTime() / 1000, //unix 时间戳
								alarm: true, //是否提醒
								alarmOffset: 600,
								allDay:
									that.paramsData.dateType == 1
										? true
										: false,
								description: '', //日历的备注
								success(res) {
									console.log(res, '调用成功')
									let id = that.scheduleId
										? that.scheduleId
										: data
									that.writeLog(id)
									// wx.showModal({
									// 	title: '提示',
									// 	content: 1,
									// 	showCancel: false
									// })
								},
								fail(res) {
									console.log(res, '调用失败')
									uni.showToast({
										title: '取消同步日历，数据已保存',
										icon: 'none',
									})
									setTimeout(() => {
										uni.$emit('refreshData', 1)
										uni.navigateBack({
											delta: 1,
											success() {
												const page =
													getCurrentPages().pop() //跳转页面成功之后
												if (!page) return
												page.onLoad({ refresh: true }) //如果页面存在，则调用 onLoad 方法
											},
										})
									}, 1000)
									// wx.showModal({
									// 	title: '提示',
									// 	// content: res.errMsg,
									// 	content: "加失败或请'设置-隐私-日历'中允许微信使用日历",
									// 	showCancel: false
									// })
									// that.$refs.popupDialog.close()
									// that.$emit('complete')
								},
								complete(res) {
									console.log(res, '调用完成成功')

									// console.log(res, '调用')
								},
							})
						} else {
							uni.showToast({
								title: '保存成功',
								icon: 'success',
							})
							setTimeout(() => {
								uni.$emit('refreshData', 1)
								uni.navigateBack({
									delta: 1,
									success() {
										const page = getCurrentPages().pop() //跳转页面成功之后
										if (!page) return
										page.onLoad({ refresh: true }) //如果页面存在，则调用 onLoad 方法
									},
								})
							}, 1000)
						}
					}
				})
		},
		getDetail() {
			let params = {
				scheduleId: this.scheduleId,
				orgId: uni.getStorageSync('orgId'),
				templateId: this.templateId,
			}
			this.$request
				.request('carer-platform/work/log/schedule/scheduleDetail', {
					method: 'post',
					data: params,
				})
				.then((res) => {
					let { data } = res
					this.paramsData = res.data
					this.entryTime = data.scheduleStandardDate
					if (data.partUserIds && data.partUserIds.length > 0) {
						this.userType = 2
						this.userData.map((item) => {
							if (data.partUserIds.includes(item.id)) {
								item.showFlag = true
							}
						})
					}
					if (data.voiceDTOS && data.voiceDTOS.length > 0) {
						// console.log('父亲调用' + data.voiceDTOS)
						this.voiceDTOS.voiceUrl = data.voiceDTOS[0].voiceUrl
						this.voiceDTOS.voiceDuration =
							data.voiceDTOS[0].voiceDuration
						this.voiceDTOS.voiceText = data.voiceDTOS[0].voiceText
					}
					// if (this.paramsData.tags.length > 0) {
					// 	this.tagList.map(item => {
					// 		if (this.paramsData.tags.includes(item.id)) {
					// 			item.active = true
					// 		}
					// 	})
					// }
					// if (data.userIds.length > 0) {
					// 	this.userData.map(item => {
					// 		if (data.userIds.includes(item.id)) {
					// 			item.showFlag = true
					// 		}
					// 	})
					// }
					// this.scheduleContent = data.content
				})
		},
	},
	created() {
		let list = [1, 2, 3, 9]
		this.getUserData()
		this.paramsData.scheduleStartTime = Number(dayjs().format('HH')) + ':00'
		this.paramsData.scheduleEndTime =
			Number(dayjs().format('HH')) + 1 + ':00'
		list.map((item) => {
			this.getLabel(item)
		})
	},
	onShow() {
		if (this.scheduleId) {
			this.getDetail()
		}
	},
	onLoad(options) {
		let { date, id, templateId } = options
		if (id) {
			this.scheduleId = id
			this.templateId = templateId === 'undefined' ? '' : templateId
		}
		this.currentDate = date
		let title = options.id ? '日程编辑' : '新增日程'
		wx.setNavigationBarTitle({
			title: '详情',
		})
	},
}
</script>

<style lang="scss" scoped>
// @import url('../../../../uni.scsss');
.text-box {
	border-radius: 6rpx;
	border: 2rpx solid #f2f2f2;
	.tab {
		align-items: center;
		justify-content: center;
		text-align: center;
		border-radius: 6rpx 6rpx 0 0;
		view {
			border-radius: 6rpx 6rpx 0 0;
			&.active {
				background-color: $primary-color;
				color: #ffffff;
			}
		}
	}
}
.content {
	border: 2rpx solid #f2f2f2;
	padding: 0 20rpx;
	.form-item {
		border-bottom: 2px solid #f2f2f2;
		line-height: 80rpx;
		padding: 5rpx 20rpx;
		label {
			width: 120rpx;
			text-align: left;
			color: #333333;
			font-weight: 500;
			font-size: 32rpx;
		}
		.label {
			border: 2rpx solid $primary-color;
			color: $primary-color;
			display: inline-block;
			margin: 5rpx;
			height: 60rpx;
			line-height: 60rpx;
			padding: 0 15rpx;
			font-size: 32rpx;
			border-radius: 6rpx;
			&.active {
				background-color: $primary-color;
				color: #ffffff;
			}
		}
	}
}
.typeLabel {
	&:nth-child(1) {
		&.active {
			background-color: #81b337 !important;
			color: #fff !important;
		}
	}
	&:nth-child(2) {
		&.active {
			background-color: #de868f !important;
			color: #fff !important;
		}
	}
}
/deep/.uni-easyinput__content-textarea {
	height: 270rpx !important;
	padding: 20rpx;
	font-size: 34rpx;
}
.add {
	position: fixed;
	bottom: 0;
	left: 0;
	width: 100%;
}

.level {
	&:nth-child(1) {
		color: $primary-color !important;
		border: 2rpx solid $primary-color !important;
		&.active {
			background-color: $primary-color !important;
			color: #fff !important;
		}
	}
	&:nth-child(2) {
		color: #eeb571 !important;
		border: 2rpx solid #eeb571 !important;
		&.active {
			background-color: #eeb571 !important;
			color: #fff !important;
		}
	}
	&:nth-child(3) {
		color: #d6837c !important;
		border: 2rpx solid #d6837c !important;
		&.active {
			background-color: #d6837c !important;
			color: #fff !important;
		}
	}
}
.normal {
	color: $primary-color !important;
	border: 2rpx solid $primary-color !important;
}
.important {
	color: #eeb571 !important;
	border: 2rpx solid #eeb571 !important;
}
.danger {
	color: #d6837c !important;
	border: 2rpx solid #d6837c !important;
}
.type {
	view {
		&:nth-child(1) {
			color: #81b337 !important;
			border: 2rpx solid #81b337 !important;
		}
		&:nth-child(2) {
			color: #ebb8bd !important;
			border: 2rpx solid #ebb8bd !important;
		}
	}
}
</style>
